import Vue from "vue"
 
import VueRouter from "vue-router"

//路由懒加载
const Home = () => import("@pages/Home");
const Search = () => import("@pages/Search");
const Login = () => import("@pages/Login");
const Register = () => import("@pages/Register");

Vue.use(VueRouter)

//重写路由器的push方法
//1,先获取VueRouter原型对象上的push方法
const lastPush = VueRouter.prototype.push

/* 
    为什么要重写push
    因为push方法返回promise实例,如果不传push的第三个参数onAbort,则push内部的catch函数没有处理异常的回调函数,
    所以如果push出错,就会直接把错误抛在浏览器上
*/

//2,重写push
/* 
    -push在VueRouter的原型对象上
    -需要给第三个参数传入一个函数才能唤起push内部捕获错误的机制
    
*/

VueRouter.prototype.push = function (
    location,
    onComplete = () => {},
    onAbort = () => {}
){
    /* 
    如果不修正this指向,
     Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'history')"
    */

     //push是VueRouter原型的方法,push函数内部的this指向VueRouter的实例即$router
    return lastPush.call(this, location, onComplete, onAbort)
}

export default new VueRouter({
    mode: "history",
    routes: [
        {path: "/home", component: Home, name: "Home"},
        {path: "/login", component: Login, name: "Login"},
        {path: "/register", component: Register, name: "Register"},
        {path: "/search", component: Search, name: "Search"},
        {path: "/", redirect: "/home"},
    ]
})